package com.sgb.kjwl.view.ui.fragment.manage.special

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentSpecialMemberBinding
import com.sgb.kjwl.databinding.ItemSpecialMemberBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.manage.special.SpecialMemberEntity
import com.sgb.kjwl.viewmodel.manage.CompanySpecialViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.DateUtils
import com.im.immodel.IMUtils
import javax.inject.Inject

class SpecialMemberFragment : AppLazyFragment() {

    @Inject
    lateinit var  mViewModel : CompanySpecialViewModel
    private var mNo : String = ""

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mBinding : FragmentSpecialMemberBinding

    private lateinit var mAdapter : SpecialMemberAdapter

    companion object{
        const val TAG = "specialMemberFragment"
        const val KEY_NO = "key_no"
        fun newInstance(no : String)  : SpecialMemberFragment {
            val fragment = SpecialMemberFragment()
            val bundle = Bundle()
            bundle.putString(KEY_NO, no)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null){
            mNo = requireArguments().getString(KEY_NO)
        }
    }



    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }



    override fun onLazyLoad() {
        isLoadMore = false
        mViewModel.getSpecialMemberList(if (mNo == "-1") "" else mNo, isLoadMore)
    }

    public fun refresh() {
        isLoadMore = false
        mViewModel.getSpecialMemberList(if (mNo == "-1") "" else mNo, isLoadMore)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_special_member, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        initRecyclerView()
        mViewModel.mSpecialMemberList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (it != null){
                if (isLoadMore){
                    mAdapter.addData(it)
                } else {
                    mAdapter.setNewData(it)
                }
            }
        })
        mViewModel.mImMsg.observe(this, {
            if (it != null){
                if (TextUtils.isEmpty(it.imAccount)){
                    Toast.makeText(context, "im账号不能为空！！", Toast.LENGTH_SHORT).show()
                    return@observe
                }
                IMUtils.getInstance().buildSingleTalking(it.imAccount)
            }
        })
    }

    @SuppressLint("UseRequireInsteadOfGet")
    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mViewModel.getSpecialMemberList(if (mNo == "-1") "" else mNo, isLoadMore)
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mViewModel.getSpecialMemberList(if (mNo == "-1") "" else mNo, isLoadMore)
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = SpecialMemberAdapter(context!!, R.layout.item_special_member)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp10), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setCallBack(object : ClickCallback{
            override fun clickAcceptance(item: SpecialMemberEntity?, position: Int) {
                if (item != null){
                    mViewModel.getDetail(context!!, item.no, "受理")
                }
            }

            override fun clickItem(item: SpecialMemberEntity?, position: Int) {
                if (item != null){
                    mViewModel.getDetail(context!!, item.no, "受理详情")
                }
            }

            override fun goToChat(item: SpecialMemberEntity?, position: Int) {
                if (item != null){
                    mViewModel.getImAccount(item.companyNo, "1") //暂时是企业
                }
            }
        })
    }


    class SpecialMemberAdapter(mContext : Context, layoutResId : Int) : BaseQuickAdapter<SpecialMemberEntity, BaseViewHolder>(layoutResId){
        private  var mItemBinging : ItemSpecialMemberBinding?= null

        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))

        private var ssb : SpannableStringBuilder?= null

        private var mCallback : ClickCallback ?= null

        fun setCallBack(callback : ClickCallback){
            this.mCallback = callback
        }

        override fun convert(helper: BaseViewHolder?, item: SpecialMemberEntity?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
            mItemBinging?.run {
                tvName.text = item!!.companyName
                setColorSpan(mContext.resources.getString(R.string.invite_business_address, item!!.address),tvBusinessAddress)
                setColorSpan(mContext.resources.getString(R.string.invite_business_operation, item.business), tvBusinessOperation)
                setColorSpan(mContext.resources.getString(R.string.invite_time, DateUtils.timestampToDateSecond(item.createTime)), tvTime)
                setColorSpan(mContext.resources.getString(R.string.special_member_contacts, item.contacts), tvContacts)
                setColorSpan(mContext.resources.getString(R.string.special_member_contact_phone, item.phone), tvContactNumber)
                //0待受理 1已同意 2已拒绝
                if (item.status == 0){
                  tvStatus.text = "待受理"
                    tvStatus.setBgColor(R.color.color_secondary_yellow)
                } else if (item.status == 1){
                   tvStatus.text = "已通过"
                    tvStatus.setBgColor(R.color.color_secondary_green)
                } else if (item.status == 2){
                    tvStatus.text = "已拒绝"
                    tvStatus.setBgColor(R.color.color_secondary_red)
                }
                tvAccept.visibility = if (item.status == 0) View.VISIBLE else View.GONE
                tvAccept.setOnClickListener {//受理
                    if (mCallback != null){
                        mCallback!!.clickAcceptance(item, helper.layoutPosition)
                    }
                }
                root.setOnClickListener {
                    if (mCallback != null){
                        mCallback!!.clickItem(item, helper.layoutPosition)
                    }
                }
                tvChat.setOnClickListener {//受理
                    if (mCallback != null){
                        mCallback!!.goToChat(item, helper.layoutPosition)
                    }
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }
    }

    interface ClickCallback{
        fun clickAcceptance(item: SpecialMemberEntity?, position : Int)
        fun clickItem(item: SpecialMemberEntity?, position : Int)
        fun goToChat(item: SpecialMemberEntity?, position : Int)
    }
}